package com.example.yiparkapplication.activity.index.activity.contactUs;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codingending.popuplayout.PopupLayout;
import com.example.yiparkapplication.R;
import com.example.yiparkapplication.constant.API;
import com.example.yiparkapplication.constant.Constant;
import com.example.yiparkapplication.entity.UserComplaints;
import com.example.yiparkapplication.util.BaseActivity;
import com.example.yiparkapplication.util.Common;
import com.example.yiparkapplication.util.CompressImage;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ContactUsActivity extends BaseActivity implements View.OnClickListener {

    private Handler handler = null;
    private TextView vContactUsType;
    private EditText vEditText;
    private TextView vTextView;
    private int status = 0;
    private ImageView unbindImg;
    private UserComplaints userComplaints = new UserComplaints();
    private List<String> pictureUriList = new ArrayList<String>();
    private int mPhotos;

    @SuppressLint("ClickableViewAccessibility")
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_contant_us_layout);
        handler = new Handler();

        //选择联系客服的类型
        vContactUsType = findViewById(R.id.id_contact_us_type);
        RelativeLayout submitType = findViewById(R.id.id_select_submit_type);
        submitType.setOnClickListener(this);

        //输入车牌输入框
        vEditText = findViewById(R.id.id_license_plate);
        vEditText.setVisibility(View.GONE);

        vEditText.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event){
                if (event.getAction() == MotionEvent.ACTION_DOWN){
                    //如果当前输入框动作为按下，这里原来是写了一个工具类来调用
//                    if ()
                }
                if(event.getAction() == MotionEvent.ACTION_UP){
                    //如果当前输入框动作为手指离开，又要干啥干啥
                }
                return true;
            }
        });

        //接触绑定车辆用的提示信息，通过计算的方式，给这个文字TextView赋值
        vTextView = findViewById(R.id.id_vehicle_unbundling_message);
        vTextView.setVisibility(View.GONE);

        //图片绑定
        unbindImg.findViewById(R.id.id_unbind_img);
        unbindImg.setOnClickListener(this);

        //最后的提交按钮
        Button button = findViewById(R.id.id_unbind_button);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v){
        switch(v.getId()){
            case R.id.id_select_submit_type:
                selectType();
                break;
            case R.id.id_unbind_img:
                getImg();
                break;
            case R.id.id_unbind_button:
                if (status == 1){
                    String plate = vEditText.getText().toString();
                    if ("".equals(plate)){
                        Toast.makeText(getApplicationContext(), "车牌号不能为空", Toast.LENGTH_LONG).show();
                        return;
                    }
                    plate = plate.toUpperCase();
                    userComplaints.setPlate(plate);
                    if (pictureUriList.size() < 3){
                        Toast.makeText(getApplicationContext(), "证件照片不足", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                //非车辆解绑，就不用检查证件照片，车牌号什么的了
                EditText editText = findViewById(R.id.id_problem_description);
                String desc = editText.getText().toString();
                if ("".equals(desc)){
                    Toast.makeText(getApplication(), "问题描述不能为空", Toast.LENGTH_LONG).show();
                    return;
                }
                SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
                String userId = pref.getString("userId", "");
                userComplaints.setUserId(userId);
                userComplaints.setDescription(desc);
                userComplaints.setStatus(status);
                mPhotos = pictureUriList.size();
                if (mPhotos > 0 ){
                    uploadFiles(pictureUriList);
                }else{
                    postMessage(userComplaints);
                }

                break;
        }
    }

    private void selectType(){
        View view = View.inflate(ContactUsActivity.this, R.layout.fragment_get_img_button_layout, null);
        final PopupLayout popupLayout = PopupLayout.init(ContactUsActivity.this, view);
        popupLayout.show();

        Button albumButton = view.findViewById(R.id.id_get_img_album);
        //为啥要设置这个内容呢，默认显示“从相册中选择”，这是为了把这个弹出框拿来复用来了，在投诉与建议用一次，在相册选择用一次
        albumButton.setText("投诉与建议");
        albumButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                popupLayout.dismiss();
                vContactUsType.setText("投诉与建议");
                vEditText.setVisibility(View.GONE);
                vEditText.setText("");
                vTextView.setVisibility(View.GONE);
                status = 0;
            }
        });
        Button cancelButton = view.findViewById(R.id.id_get_img_cancel);
        cancelButton.setText("车辆解绑");
        cancelButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                popupLayout.dismiss();
                vContactUsType.setText("车辆解绑");
                vEditText.setVisibility(View.VISIBLE);
                vTextView.setVisibility(View.VISIBLE);
                status = 1;
            }
        });
    }

    private void getImg(){
        View view = View.inflate(ContactUsActivity.this, R.layout.fragment_get_img_button_layout, null);
        final PopupLayout popupLayout = PopupLayout.init(ContactUsActivity.this, view);
        popupLayout.show();

        Button albumButton = view.findViewById(R.id.id_get_img_album);
        albumButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                if (ContextCompat.checkSelfPermission(ContactUsActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(ContactUsActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                }else{
                    openAlbum();
                    popupLayout.dismiss();
                }
            }
        });
        Button cancelButton = view.findViewById(R.id.id_get_img_cancel);
        cancelButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                popupLayout.dismiss();
            }
        });
    }

    private void openAlbum(){
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/**");
        //打开相册
        startActivityForResult(intent, Constant.CHOOSE_PHOTO);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResult){
        switch(requestCode){
            case 1:
                if (grantResult.length > 0 && grantResult[0] == PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                }else{
                    Toast.makeText(getApplicationContext(), Constant.REFUSED_PERMISSION, Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode){
            case Constant.CHOOSE_PHOTO:
                if (resultCode ==RESULT_OK){
                    if (Build.VERSION.SDK_INT >= 19){
                        //4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    }else{
                        //4.4以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data);
                    }
                }
        }
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data){
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)){
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1]; //解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            //如果是content类型的uri，则通过普通方式处理
            imagePath = getImagePath(uri, null);
        }else if("file".equalsIgnoreCase(uri.getScheme())){
            imagePath = uri.getPath();
        }
        displayImage(imagePath);
    }

    private void handleImageBeforeKitKat(Intent data){
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection){
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath){
        if (imagePath != null){
            pictureUriList.add(imagePath);
            showImg(pictureUriList);
        }else{
            Toast.makeText(getApplicationContext(), Constant.FAILED_TO_GET_IMAGE, Toast.LENGTH_LONG).show();
        }
    }

    public void showImg(List<String> prictureUriList){
        RecyclerView vRecyclerView = findViewById(R.id.id_papers_img);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        vRecyclerView.setLayoutManager(layoutManager);
        ContactUsAdapter adapter = new ContactUsAdapter(pictureUriList, ContactUsActivity.this);
        vRecyclerView.setAdapter(adapter);
        if (pictureUriList.size() == 4){
            unbindImg.setVisibility(View.GONE);
        }else{
            unbindImg.setVisibility(View.VISIBLE);
        }
    }

    private void uploadFiles(List<String> pictureUriList){
        MediaType mediaType = MediaType.parse("multipart/form-data; charset=uth-8");
        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("type", "4");
        for (int i=0; i < pictureUriList.size(); i++){
            Bitmap bitmap = CompressImage.getImage(pictureUriList.get(i));
            File file = CompressImage.getFile(bitmap, i);
            requestBodyBuilder.addFormDataPart("files", file.getName(), RequestBody.create(mediaType, new File(pictureUriList.get(i))));
        }
        RequestBody requestBody = requestBodyBuilder.build();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_POST_UPLOAD_FILES)
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    JSONArray ja = joOut.getJSONArray("object");
                    switch(mPhotos){
                        case 0:
                            break;
                        case 1:
                            userComplaints.setPhoto1(ja.get(0).toString());
                            break;
                        case 2:
                            userComplaints.setPhoto1(ja.get(0).toString());
                            userComplaints.setPhoto2(ja.get(1).toString());
                            break;
                        case 3:
                            userComplaints.setPhoto1(ja.get(0).toString());
                            userComplaints.setPhoto2(ja.get(1).toString());
                            userComplaints.setPhoto3(ja.get(2).toString());
                            break;
                        case 4:
                            userComplaints.setPhoto1(ja.get(0).toString());
                            userComplaints.setPhoto2(ja.get(1).toString());
                            userComplaints.setPhoto3(ja.get(2).toString());
                            userComplaints.setPhoto4(ja.get(3).toString());
                            break;
                    }
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), "图片上传成功", Toast.LENGTH_LONG).show();
                    Looper.loop();
                }else{
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        });
    }

    private void postMessage(UserComplaints userComplaints){
        String json = JSONObject.toJSONString(userComplaints);
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_ADD_USER_COMPLAINTS)
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException{
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    Looper.prepare();
                    Intent intent = new Intent();
                    setResult(Constant.POST_CONTACT_US_CODE, intent);
                    finish();
                    Looper.loop();
                }else{
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        });
    }
}
